<template>
	<view class="content">
		<image src="../../static/logo.png" class="logoImg"></image>
		<text class="welcome-text">欢迎使用鑫三元催化风向标</text>
		<text class="login-text">(此系统为内部报价系统，必须登录授权)</text>
		<u-form :model="loginForm" style="margin-top: 4%;width: 70%;">
			<u-form-item label="手机号" left-icon="account" label-width="140" :left-icon-style="greenStyle"
				:label-style="greenStyle">
				<u-input v-model="loginForm.username" placeholder="请输入手机号" />
			</u-form-item>
			<u-form-item label="密码" left-icon="lock" label-width="140" :left-icon-style="greenStyle"
				:label-style="greenStyle" v-model="loginForm.password">
				<u-input v-model="pseudoPassword" type="password" :password-icon="passwordIcon" placeholder="请输入密码" @input="removePseudoPassword"/>
			</u-form-item>
			<u-form-item label="验证码" left-icon="hourglass" label-width="140" :left-icon-style="greenStyle"
				:label-style="greenStyle">
				<view class="flex-row">
					<u-input v-model="loginForm.code" placeholder="请输入验证码" />
					<image class="login-code" :src="codeUrl" @click="getCode"></image>
				</view>
			</u-form-item>
			<u-form-item label="记住我" label-width="140" :label-style="greenStyle" label-position="left"
				label-align="left">
				<u-checkbox-group active-color="#55aa7f">
					<u-checkbox v-model="loginForm.rememberMe" />
				</u-checkbox-group>
			</u-form-item>
		</u-form>
		<u-button type="success" @click="toLogin" size="medium" style="margin-top: 6%;">授权登录</u-button>
		<view class="flex-column content-bottom" @click="gotoCalculator">
			<image src="../../static/calculator-select.png"></image>
			<text>报价计算器</text>
		</view>
		<u-toast ref="uToast" />
		<u-no-network></u-no-network>
	</view>
</template>

<script>
	import {
		encrypt
	} from '@/utils/rsaEncrypt';
	import store from '@/store/index.js'; //需要引入store
	import {
		mapState
	} from 'vuex' //引入mapState
	import {
		getCodeImg,
		postLogin,
		getUnitPrice
	} from "@/common/js/api/api.js";
	import WXBizDataCrypt from "@/utils/WXBizDataCrypt.js";
	export default {
		data() {
			return {
				greenStyle: {
					color: '#55aa7f'
				},
        //伪密码
        pseudoPassword: '',
				codeUrl: '',
				passwordIcon: true,
				loginForm: {
					username: '',
					password: '',
					code: '',
					uuid: '',
					wechatCode: '',
					rememberMe: false
				}
			}
		},
		computed: {
			...mapState({
				nickName: state => state.user.nickName,
				openId: state => state.adminUser.openId,
				sessionKey: state => state.adminUser.sessionKey
			}),
		},
		onLoad() {
			uni.startPullDownRefresh();
			this.onShareAppMessage();
			this.onShareTimeline();
		},
		onPullDownRefresh() {
			this.getCode();
			this.loadForm();
			this.getPseudPassword();
			getUnitPrice().then(res => {
				var rate = res.data.usdRate / 31.1035;
				res.data.pallBid = Math.round(res.data.pallBid * rate);
				res.data.rhodBid = Math.round(res.data.rhodBid * rate);
				res.data.platBid = Math.round(res.data.platBid * rate);
				wx.setStorageSync('unitPrice', res.data);
			})
			setTimeout(function () {
				uni.stopPullDownRefresh();
			}, 500);
		},
		onShow() {
			this.getPseudPassword();
			uni.setStorageSync('carType', '');
		},
		methods: {
			/**
			 * 对记住的密码进行删除或输入新密码时移出伪密码
			 */
			removePseudoPassword() {
			  if (this.pseudoPassword.indexOf('*') != -1) {
			    this.pseudoPassword = '';
					this.passwordIcon = true;
			  }
				if(this.pseudoPassword == '') {
					this.passwordIcon = true;
				}
			},
			getPseudPassword() {
				this.pseudoPassword = uni.getStorageSync('pseudoPassword');
				if(this.pseudoPassword.indexOf('*') != -1) {
					this.passwordIcon = false;
				}
			},
			onShareAppMessage() {
				const promise = new Promise(resolve => {
					setTimeout(() => {
						resolve({
							title: '鑫三元催化风向标'
						})
					}, 1000)
				})
				return {
					title: '鑫三元催化风向标',
					promise 
				}
			},
			onShareTimeline() {
				const promise = new Promise(resolve => {
					setTimeout(() => {
						resolve({
							title: '鑫三元催化风向标'
						})
					}, 1000)
				})
				return {
					title: '鑫三元催化风向标',
					promise 
				}
			},
			loadForm() {
				var oldForm = wx.getStorageSync('loginForm');
				this.loginForm.username = oldForm.username;
				this.loginForm.password = oldForm.password;
				this.loginForm.rememberMe = oldForm.rememberMe;
			},
			getCode() {
				getCodeImg().then((res) => {
					res = res.data;
					this.codeUrl = res.img;
					this.loginForm.uuid = res.uuid;
					this.loginForm.code = ''
				}).catch((err) => {
					uni.showToast({
						title: err.response.data.message,
						icon: "error",
						duration: 2000
					});
				});
			},
			toLogin() {
				if(this.pseudoPassword.indexOf('*') == -1) {
					this.loginForm.password = this.pseudoPassword;
				}else {
					let oldForm = wx.getStorageSync('loginForm');
					this.loginForm.password = oldForm.password;
				}
				let num = '';
				let pseudoPassword = num.toString().padStart(this.pseudoPassword.toString().length, '*');
				uni.setStorageSync('pseudoPassword',pseudoPassword);
				if (this.loginForm.username == '' || this.loginForm.password == '' || this.loginForm.code == '') {
					this.pseudoPassword = '';
					this.$refs.uToast.show({
						title: '请先填写信息',
						type: 'error'
					})
				} else {
					wx.getUserProfile({
						desc: '展示用户信息', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
						success: (res) => {
							let userInfo = res.userInfo;
							let user = res.userInfo;
							store.commit('user/setUser', {
								nickName: user.nickName,
								avatarUrl: user.avatarUrl
							});
							wx.setStorageSync('wechatUser', user)
							wx.login({
								provider: 'weixin',
								success: (res) => {
									uni.showLoading({
										title: '加载中'
									});
									let oldForm = wx.getStorageSync('loginForm');
									if (oldForm != null) {
										if (oldForm.password != this.loginForm.password) {
											this.loginForm.password = encrypt(this.loginForm.password);
										}
									} else {
										this.loginForm.password = encrypt(this.loginForm.password);
									}
									this.loginForm.wechatCode = res.code;
									postLogin(this.loginForm).then((res1) => {
										store.commit('adminUser/setAdminUser', {
											token: res1.data.token,
											user: res1.data.user
										});
										wx.setStorageSync('user', res1.data.user)
										wx.setStorageSync('token', res1.data.token)
										this.$refs.uToast.show({
											title: '登录成功',
											type: 'success'
										})
										if (this.loginForm.rememberMe) {
											let newForm = {
												username: this.loginForm.username,
												password: this.loginForm.password,
												rememberMe: this.loginForm.rememberMe
											}
											wx.setStorageSync('loginForm', newForm);
										} else {
											wx.removeStorageSync('loginForm');
										}
										setTimeout(() => {
											uni.switchTab({
												url: '../tabBar/brand/brand'
											})
										}, 1000);
									}).catch((res1) => {
										this.getCode();
										this.$refs.uToast.show({
											title: res1.message,
											type: 'failed'
										})
										this.loginForm.password = '';
									}).finally(() => {
										uni.hideLoading();
									});
								}
							});
						},
						fail: (err) => {
							this.$refs.uToast.show({
								title: '为了您的正常使用,请授权登录',
								type: 'primary'
							})
						}
					})
				}
			},
			gotoCalculator() {
				uni.navigateTo({
					url: '../publicCalculator/publicCalculator'
				})
			}
		}
	}
</script>

<style>
	@import url("../../common/css/login.css");
</style>
